
Page({
  data: {
    startDate: '',
    endDate: '',
    classList: [{ id: 0, name: '全部班级' }],
    classIndex: 0,
    statistics: {
      totalDays: 0,
      totalStudents: 0,
      attendanceRate: '0%',
      lateRate: '0%'
    },
    activeTab: 'course', // 默认显示课程考勤
    dailyStats: [],
    studentStats: [],
    courseStats: [], // 添加课程统计数据
    // 使用 u-charts 的图表配置
    chartData: {
      categories: [],
      series: [
        {
          name: '出勤',
          data: []
        },
        {
          name: '迟到',
          data: []
        },
        {
          name: '缺勤',
          data: []
        }
      ]
    },
    opts: {
      title: {
        name: '考勤趋势',
        fontSize: 15,
        color: '#666666'
      },
      legend: {
        show: true,
        position: 'bottom',
        float: 'center'
      },
      xAxis: {
        disableGrid: true,
        rotateLabel: true
      },
      yAxis: {
        data: [
          {
            min: 0
          }
        ]
      },
      extra: {
        line: {
          type: 'curve',
          width: 2
        }
      }
    }
  },

  onLoad: function() {
    // 设置默认日期范围（最近30天）
    const today = new Date();
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(today.getDate() - 30);
    
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };
    
    this.setData({
      startDate: formatDate(thirtyDaysAgo),
      endDate: formatDate(today)
    });
    
    // 获取班级列表
    this.fetchClassList();
    
    // 获取统计数据
    this.fetchStatisticsData();
  },

  // 获取班级列表
  fetchClassList: function() {
    const app = getApp();
    wx.request({
      url: `${app.globalData.serverUrl}/api/admin/classes`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          // 添加"全部班级"选项
          const classList = [{ id: 0, name: '全部班级' }, ...res.data];
          this.setData({ classList });
        }
      },
      fail: (err) => {
        console.error('获取班级列表失败:', err);
      }
    });
  },

  // 获取统计数据
  fetchStatisticsData: function() {
    wx.showLoading({
      title: '加载中...',
    });
    
    const app = getApp();
    const classId = this.data.classList[this.data.classIndex].id;
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/admin/attendance/statistics`,
      method: 'GET',
      data: {
        startDate: this.data.startDate,
        endDate: this.data.endDate,
        classId: classId === 0 ? '' : classId,
        groupBy: 'course' // 添加参数，按课程分组
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          console.log('获取到的统计数据:', res.data);
          
          // 处理日期统计数据，添加出勤率
          const dailyStats = res.data.dailyStats.map(item => {
            return {
              ...item,
              rate: item.total > 0 ? (item.present / item.total * 100).toFixed(2) + '%' : '0%'
            };
          });
          
          // 处理学生统计数据，添加出勤率
          const studentStats = res.data.studentStats.map(item => {
            return {
              ...item,
              rate: item.total > 0 ? (item.present / item.total * 100).toFixed(2) + '%' : '0%'
            };
          });
          
          // 处理课程统计数据
          const courseStats = res.data.courseStats ? res.data.courseStats.map(item => {
            return {
              ...item,
              rate: item.total > 0 ? (item.present / item.total * 100).toFixed(2) : '0'
            };
          }) : [];
          
          // 准备图表数据 - 使用课程数据
          let categories = [];
          let presentData = [];
          let lateData = [];
          let absentData = [];
          
          if (courseStats.length > 0) {
            // 使用课程数据
            categories = courseStats.map(item => item.courseName);
            presentData = courseStats.map(item => item.present);
            lateData = courseStats.map(item => item.late);
            absentData = courseStats.map(item => item.absent);
          } else {
            // 如果没有课程数据，使用日期数据
            const sortedData = [...dailyStats].sort((a, b) => {
              return new Date(a.date) - new Date(b.date);
            });
            
            categories = sortedData.map(item => item.date);
            presentData = sortedData.map(item => item.present);
            lateData = sortedData.map(item => item.late);
            absentData = sortedData.map(item => item.absent);
          }
          
          this.setData({
            statistics: res.data.overview,
            dailyStats: dailyStats,
            studentStats: studentStats,
            courseStats: courseStats,
            chartData: {
              categories: categories,
              series: [
                {
                  name: '出勤',
                  data: presentData
                },
                {
                  name: '迟到',
                  data: lateData
                },
                {
                  name: '缺勤',
                  data: absentData
                }
              ]
            }
          });
        } else {
          wx.showToast({
            title: res.data.message || '获取统计数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求统计数据失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 开始日期变更
  startDateChange: function(e) {
    this.setData({
      startDate: e.detail.value
    });
  },

  // 结束日期变更
  endDateChange: function(e) {
    this.setData({
      endDate: e.detail.value
    });
  },

  // 班级变更
  classChange: function(e) {
    this.setData({
      classIndex: e.detail.value
    });
  },

  // 查询统计
  queryStatistics: function() {
    this.fetchStatisticsData();
  },

  // 切换标签页
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
  },

  // 导出统计
  exportStatistics: function() {
    wx.showLoading({
      title: '准备导出...',
    });
    
    const app = getApp();
    const classId = this.data.classList[this.data.classIndex].id;
    
    // 构建下载链接
    const downloadUrl = `${app.globalData.serverUrl}/api/admin/attendance/export?startDate=${this.data.startDate}&endDate=${this.data.endDate}&classId=${classId === 0 ? '' : classId}&groupBy=${this.data.activeTab}`;
    
    // 使用小程序的下载文件API
    wx.downloadFile({
      url: downloadUrl,
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200) {
          // 打开文件
          wx.openDocument({
            filePath: res.tempFilePath,
            fileType: 'xlsx',
            success: function() {
              console.log('打开文档成功');
              wx.showToast({
                title: '导出成功',
                icon: 'success'
              });
            },
            fail: function(error) {
              console.error('打开文档失败:', error);
              wx.showToast({
                title: '无法打开文件',
                icon: 'none'
              });
            }
          });
        } else {
          wx.showToast({
            title: '导出失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('下载文件失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '导出失败，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  }
});